package br.com.gaspar.academia.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter(servletNames={"Faces Servlet"})
public class SegurancaFilter implements Filter {
	
	private static List<String> listaBranca = new ArrayList<String>();
	
	static{
		listaBranca.add("/index.jsf");
		listaBranca.add("/localizacao.jsf");
		listaBranca.add("/contato.jsf");
		listaBranca.add("/servicos.jsf");
	}

	@Override
	public void doFilter (ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		Boolean segurancaAtiva = true;
		if(segurancaAtiva){
			HttpServletRequest req = (HttpServletRequest) request ;
			HttpSession session = req.getSession();
			String contextoWeb = req.getContextPath(); 
			String requestURI =  req.getRequestURI();
			String recurso = requestURI.substring(contextoWeb.length());
			
			if(!listaBranca.contains(recurso)){
				if (session.getAttribute("usuarioLogado") != null
						|| requestURI.endsWith("/index.jsf")) {
				} else {
					HttpServletResponse res = (HttpServletResponse)response ;
					res.sendRedirect(req.getContextPath() + "/index.jsf");
				}
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init ( FilterConfig filterConfig ) throws ServletException {

	}

	@Override
	public void destroy () {

	}
}
